<template>
  <div class="cpk-chart">
    <el-row :gutter="20">
      <el-col :span="14">
        <chart-view class="chart-content" :chart-option="chartOpt" :auto-resize="true" width="100%" />
        <chart-view class="chart-content" :chart-option="chartOpt" :auto-resize="true" width="100%" />
      </el-col>
      <el-col :span="10">
        <table class="table">
          <tbody>
            <tr v-for="(item, index) in analysisDataGroupUp" :key="index">
              <td v-for="(child, childIndex) in item" :key="childIndex">{{ child }}</td>
            </tr>
          </tbody>
        </table>
        <table class="table">
          <tbody>
            <tr v-for="(item, index) in analysisDataGroupDown" :key="index">
              <td v-for="(child, childIndex) in item" :key="childIndex">{{ child }}</td>
            </tr>
          </tbody>
        </table>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import Vue from 'vue';
import ChartView from '@/components/chart/index.vue';
// import { Descriptions } from 'element-ui'
// Vue.use(Descriptions);
export default {
    name: 'cpkChart',
    components: {
        ChartView
    },
    data() {
        return {
            chartOpt: {
                tooltip: {
                    // 触发类型
                    trigger: 'axis',
                    // 是配置坐标轴指示器的快捷方式
                    axisPointer: {
                        type: 'cross',
                        crossStyle: {
                            color: '#999'
                        }
                    }
                },
                // 工具栏
                toolbox: {
                    // 数据视图工具，可以展现当前图表所用的数据，编辑后可以动态更新。
                    show: true,
                    feature: {
                        dataView: { show: true, readOnly: false },
                        magicType: { show: true, type: ['line', 'bar'] },
                        restore: { show: true },
                        saveAsImage: { show: true }
                    }
                },
                legend: {
                    // 图例的数据数组。
                    data: ['Evaporation', 'Precipitation', 'Temperature']
                },
                xAxis: [
                    {
                        type: 'category',
                        data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
                        axisPointer: {
                            type: 'shadow'
                        }
                    }
                ],
                yAxis: [
                    {
                        type: 'value',
                        name: 'Precipitation',
                        min: 0,
                        max: 250,
                        interval: 50,
                        axisLabel: {
                            formatter: '{value} ml'
                        }
                    },
                    {
                        type: 'value',
                        name: 'Temperature',
                        min: 0,
                        max: 25,
                        interval: 5,
                        axisLabel: {
                            formatter: '{value} °C'
                        }
                    }
                ],
                series: [
                    {
                        name: 'Evaporation',
                        type: 'bar',
                        tooltip: {
                            valueFormatter: function (value) {
                                return value + ' ml';
                            }
                        },
                        data: [
                            2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3
                        ]
                    },
                    {
                        name: 'Temperature',
                        type: 'line',
                        yAxisIndex: 1,
                        tooltip: {
                            valueFormatter: function (value) {
                                return value + ' °C';
                            }
                        },
                        data: [2.0, 2.2, 3.3, 4.5, 6.3, 10.2, 20.3, 23.4, 23.0, 16.5, 12.0, 6.2]
                    }
                ]
            },
            analysisDataGroupUp: [
                ['总样本数', 100, '子组大小', 12, '', ''],
                ['平均值', 96, '最大值', 150, '最小值', 63],
                ['上规格', 85, '目标值', 65, '下规格', 32],
                ['+3Sigma', -4, '-3Sigma', +6, '', '']
            ],
            analysisDataGroupDown: [
                ['', '组内', '整体'],
                ['STDEV', 1, 2],
                ['CPK', 33, 23],
                ['CP', 12, 33],
                ['CPL', 52, 63],
                ['CPU', 36, 23],
                ['PPM < LSL', 123, 321],
                ['PPM > USL', 96, 102],
                ['PPM Total', 63, 63],
            ],
            chartList: []
        }
    },

    methods: {
        init() {

        },
        getParam(low, mean, up, top, lsl, usl) {
            const res = {};
            res['low'] = this.getFloat(low);
            res['mean'] = this.getFloat(mean);
            res['up'] = this.getFloat(up);
            res['top'] = this.getFloat(top);
            res['lsl'] = this.getFloat(lsl);
            res['usl'] = this.getFloat(usl);
            return res;
        },
        getFloat(numbers, digit = 3) {
            return (numbers.toFixed(digit) / 1).toString();
        },
        getNormalDistributionOption(data) {
            const normalDistributionY = [];

            // const mean = parseFloat(this.datas[0].data.stdPlot.mean);
            // const stdev = parseFloat(this.datas[0].data.stdPlot.stdev);
            // const x = this.datas[0].data.stdPlot.xaxis.split(',');
            // const y = this.datas[0].data.stdPlot.yaxis.split(',')
            //
            // const low = mean - 3 * stdev;
            // const up = mean + 3 * stdev;
            let mean = data.mean;
            let stdev = data.stdev
            let dataX = data.dataX
            const dataY = data.dataY
            const low = data.negativeThreeSigma;
            const up = data.positiveThreeSigma
            const lsl = data.lsl
            const usl = data.usl
            const standardValue = String(data.standardValue)
            const proportionArray = data.proportionArray
            const proportionTarget = data.proportionTarget
            const variance = data.variance
            const ariance = data.ariance
            // dataX = this.addParam(dataX, low.toFixed(0).toString());
            // dataX = this.addParam(dataX, mean.toFixed(0).toString());
            // dataX = this.addParam(dataX, up.toFixed(0).toString());

            // var top = getTop(y);

            const top = (1 / Math.sqrt(2 * Math.PI) * stdev);
            const mar = this.getParam(low, mean, up, top, lsl, usl);
            // console.log('mar', mar)
            // console.log(dataX);
            let ride = 1;

            //  stdev=this.convertValue(stdev)
            //  mean=this.convertValue(mean)

            //ride=Math.pow(10,mean.toString().split(".")[1].length)
            ride = Math.pow(10, 3)

            let meanResult = mean * ride
            let stdevResult = stdev * ride
            for (let j = 0; j < dataX.length; j++) {
                let value = dataX[j] //this.convertValue(dataX[j])
                const res = this.fun(value * ride, meanResult, stdevResult, variance).toFixed(7);
                //const res = this.gaussian(value, meanResult, stdevResult).toFixed(3);
                normalDistributionY.push(res);
            }
            const colors = ['#7CCD7C', '#d14a61', '#675bba', '#870eff'];


            const option = {
                color: colors,
                title: {
                    show: true,
                    text: data.title,
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'cross'
                    },
                    formatter: "{b0}<br/>{a0}: {c0}<br />{a2}: {c2}%"
                },
                grid: {
                    left: '10%',
                    right: '10%',
                },
                toolbox: {
                    feature: {
                        dataView: { show: true, readOnly: false },
                        restore: { show: true },
                        saveAsImage: { show: true }
                    },
                    orient: "vertical",
                    top: "middle"
                },
                legend: {
                    data: ['样本数'],
                    top: 'bottom'
                },
                xAxis: [
                    {
                        type: 'category',
                        axisTick: {
                            alignWithLabel: true
                        },
                        data: dataX,
                    }
                ],
                yAxis: [
                    {
                        type: 'value',
                        name: '样本数',
                        splitNumber: 10,
                        position: 'left',
                        splitLine: false,
                        axisLine: {
                            lineStyle: {
                                color: colors[0]
                            }
                        },
                        axisLabel: {
                            formatter: '{value}'
                        }
                    },
                    {
                        type: 'value',
                        name: '正态分布',
                        position: 'right',
                        show: false,
                        axisLine: {
                            lineStyle: {
                                color: colors[1]
                            }
                        },
                        // axisLabel: {
                        //     formatter: '{value}'
                        // },
                        splitLine: false,
                    }, {
                        type: 'value',
                        name: '百分比',
                        position: 'right',
                        axisLine: {
                            lineStyle: {
                                color: colors[1]
                            }
                        },
                        axisLabel: {
                            formatter: '{value}%',
                        },
                        splitLine: false,
                        min: 0,
                        max: proportionTarget
                    }

                ],
                series: [
                    {
                        name: '样本数',
                        type: 'bar',
                        yAxisIndex: 0,
                        data: dataY,
                        animation: false,
                        barCategoryGap: 0, // 去掉柱状图之间的间隙
                    },
                    {
                        name: '正态分布',
                        type: 'line',
                        smooth: true,
                        animation: false,
                        yAxisIndex: 1,
                        label: {
                            show: false
                        },
                        data: normalDistributionY,
                        tooltip: null
                    },

                    {
                        name: '百分比',
                        type: 'line',
                        animation: false,
                        yAxisIndex: 2,
                        data: proportionArray,
                        itemStyle: {
                            opacity: 0
                        },
                        lineStyle: {
                            opacity: 0
                        },
                        tooltip: {
                            formatter: "{c}%"
                        },
                        opacity: 0
                    },

                    {
                        type: 'line',
                        animation: false,
                        markLine: {
                            lineStyle: {
                                width: 2,
                                type: 'solid',  // 'dotted'虚线 'solid'实线
                            },
                            data: [{ name: '+3σ', xAxis: mar.up }, { name: 'mean', xAxis: mar.mean }, { name: '-3σ', xAxis: mar.low }],
                            label: {
                                show: true,
                                color: 'black',
                                formatter: function (params) {
                                    return `${params.name}`
                                },
                            }
                        }
                    },
                    {
                        type: 'line',
                        animation: false,
                        markLine: {
                            lineStyle: {
                                width: 2,
                                type: 'dotted',  // 'dotted'虚线 'solid'实线
                            },
                            data: [{ name: 'LSL', xAxis: mar.lsl }, { name: 'CL', xAxis: standardValue }, { name: 'USL', xAxis: mar.usl }],
                            label: {
                                show: true,
                                color: 'black',
                                formatter: function (params) {
                                    return `${params.name}`
                                },
                            }
                        }
                    },
                ],
            }
            return option;
        },

        // 生成多个charts
        showNormalDistributionChart(data, i) {
            this.Echarts.normalDistributionChart[i] = echarts.init(document.getElementById(`normalDistributionChart-${i}`));
            var option = EchartsClass.getNormalDistributionOption(data);
            this.Echarts.normalDistributionChart[i].setOption(option);
            this.Echarts.normalDistributionChart[i].on('dblclick', (params) => {
                const option = this.Echarts.NormalDistributionChart[i].getOption()
                const lineCode = option.title[0].text.split(' ')[0]
                const itemName = option.title[0].text.split(' ')[1]
                if (params.value < data.standardValue) {
                    const record = {
                        type: 'CPKANALYSI',
                        manufactureDate: params.name,
                        partNo: this.model.partNo,
                        lineCode: lineCode,
                        parameterName: itemName,
                    }
                    this.spcRecord = record
                    this.getAbnormalReasonDetail(record)
                    $('#abnormalReasonModal').modal('show');
                }
            })
        },

        getData() {
            let index = 0
            // this.setEchartsList("cpk");


            const spcQueryParam = this.$parent.getQueryParameter();

            this.httpService.post(Config.API_URL.SPC.GET_SPC_CPK_DATA_URL, spcQueryParam,
                (successful, dataSet, res) => {
                    if (dataSet.stateCode === 'SYSTEM_SUCCESS') {
                        const spcStatisticsResults = this._get(dataSet, 'data', [])
                        for (let i = 0; i < spcStatisticsResults.length; i++) {
                            const spcStatisticsResult = spcStatisticsResults[i];
                            const title = this._get(spcStatisticsResult, 'reportName', '')
                            const sampleData = this._get(spcStatisticsResult, 'sampleData', [])
                            const sampleCount = this._get(spcStatisticsResult, 'sampleCount', 0)
                            const cpkSubgroupSize = this.settingInfo.cpkSubgroupSize
                            const maxValue = this._get(spcStatisticsResult, 'maxValue', 0)
                            const minValue = this._get(spcStatisticsResult, 'minValue', 0)

                            const cpkAnalysisData = this._get(spcStatisticsResult, 'cpkAnalysisResult', {})
                            const normalDistributionDataX = this._get(spcStatisticsResult, 'cpkAnalysisResult.itemValueArray', [])
                            const normalDistributionDataY = this._get(spcStatisticsResult, 'cpkAnalysisResult.itemValueCountArray', [])
                            const negativeThreeSigma = this._get(cpkAnalysisData, 'negativeThreeSigma', 0)
                            const positiveThreeSigma = this._get(cpkAnalysisData, 'positiveThreeSigma', 0)
                            const mean = this._get(cpkAnalysisData, 'sampleMean', 0)
                            const stdev = this._get(cpkAnalysisData, 'standardDevition', 0)
                            const cpk = this._get(cpkAnalysisData, 'cpk', 0)
                            const cp = this._get(cpkAnalysisData, 'cp', 0)
                            const cpl = this._get(cpkAnalysisData, 'cpl', 0)
                            const cpu = this._get(cpkAnalysisData, 'cpu', 0)
                            const ppkStdev = this._get(cpkAnalysisData, 'ppkStandardDevition', 0)
                            const ppk = this._get(cpkAnalysisData, 'ppk', 0)
                            const pp = this._get(cpkAnalysisData, 'pp', 0)
                            const ppl = this._get(cpkAnalysisData, 'ppl', 0)
                            const ppu = this._get(cpkAnalysisData, 'ppu', 0)
                            const ppkPpmLessThanLsl = this._get(cpkAnalysisData, 'ppkPpmLessThanLs', 0)
                            const ppkPpmGreaterThanUsl = this._get(cpkAnalysisData, 'ppkPpmGreaterThanUsl', 0)
                            const ppkPpmFail = this._get(cpkAnalysisData, 'ppkPpmFail', 0)
                            const cpkPpmLessThanLsl = this._get(cpkAnalysisData, 'cpkPpmLessThanLs', 0)
                            const cpkPpmGreaterThanUsl = this._get(cpkAnalysisData, 'cpkPpmGreaterThanUsl', 0)
                            const cpkPpmFail = this._get(cpkAnalysisData, 'cpkPpmFail', 0)
                            const lsl = this._get(spcStatisticsResult, 'lsl', '')
                            const cl = this._get(spcStatisticsResult, 'standardValue', 0)
                            const usl = this._get(spcStatisticsResult, 'usl', '')
                            const proportionArray = this._get(cpkAnalysisData, 'proportionArray', [])
                            const proportionTarget = this._get(cpkAnalysisData, 'proportionTarget', 0)
                            const variance = this._get(cpkAnalysisData, 'variance', 0)
                            const ariance = this._get(cpkAnalysisData, 'ariance', 0)
                            const specificationCenterValue = this._get(cpkAnalysisData, 'specificationCenterValue', 0)
                            const standardValue = this._get(spcStatisticsResult, 'standardValue', 0)
                            const normalDistributionData = {
                                dataX: normalDistributionDataX,
                                dataY: normalDistributionDataY,
                                title: title,
                                mean: mean,
                                stdev: stdev,
                                lsl: lsl,
                                usl: usl,
                                positiveThreeSigma: positiveThreeSigma,
                                negativeThreeSigma: negativeThreeSigma,
                                proportionArray: proportionArray,
                                proportionTarget: proportionTarget,
                                variance: variance,
                                ariance: ariance,
                                specificationCenterValue: specificationCenterValue,
                                standardValue: standardValue
                            }

                            const analysisDataGroupUp = [
                                ['总样本数', sampleCount, '子组大小', cpkSubgroupSize, '', ''],
                                ['平均值', mean, '最大值', maxValue, '最小值', minValue],
                                ['上规格', usl, '目标值', cl, '下规格', lsl],
                                ['+3Sigma', positiveThreeSigma.toFixed(3), '-3Sigma', negativeThreeSigma.toFixed(3), '', ''],
                            ]
                            const analysisDataGroupDown = [
                                ['', '组内', '整体'],
                                ['STDEV', stdev, ppkStdev],
                                ['CPK', cpk, ppk],
                                ['CP', cp, pp],
                                ['CPL', cpl, ppl],
                                ['CPU', cpu, ppu],
                                ['PPM < LSL', cpkPpmLessThanLsl, ppkPpmLessThanLsl],
                                ['PPM > USL', cpkPpmGreaterThanUsl, ppkPpmGreaterThanUsl],
                                ['PPM Total', cpkPpmFail, ppkPpmFail],
                            ]
                            var options = this.getNormalDistributionOption(normalDistributionData)
                            this.chartList.push(options)

                            // this.analysisDataUpAll.push(analysisDataGroupUp)
                            // this.analysisDataDownAll.push(analysisDataGroupDown)
                            // this.cpkDatas.push('data')
                            // setTimeout(() => {
                            //     this.showNormalDistributionChart(normalDistributionData, i)
                            //     //this.gridOptions.api.setRowData(this.gridData);
                            // }, 50);
                        }


                        // this.gridData = _.union(this.gridData, sampleData)
                        // this.analysisDataAll.push(analysisData)

                    } else {
                        toastr.error(
                            dataSet.messageCode ? this.translate.instant(dataSet.messageCode, { value: this.translate.instant('PART') })
                                : dataSet.message);
                    }
                },
                (successful, msg, err) => {
                    toastr.error(msg);
                }
            );
        }

    }
}
</script>

<style lang="scss" scoped>
.cpk-chart {
  .table {
    margin-bottom: 10px;

    // 滚动条默认宽度是16px 将thead的宽度减16px
    thead {
      width: calc(100% - 1em);
    }

    tbody {
      border: 1px solid #ddd;
      border-bottom: none;

      tr {
        border-bottom: 1px solid #ddd;

        td {
          border-right: 1px solid #ddd;
        }

        .last-cell {
          border-right: none;
        }
      }

      tr:nth-child(even) {
        background: #fbfce5 !important;
      }

      .text-blue {
        color: #5379de;
      }

      .width-label {
        width: 104px;
      }
    }
  }
}
</style>